package com.then.component.login.ui.login;

import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.ViewModel;

import com.then.architecture.data.dto.Resource;
import com.then.basic.socket.ThreadUtil;
import com.then.component.login.LoginParams;
import com.then.component.login.dto.Login;
import com.then.component.login.repository.LoginAction;
import com.then.component.login.repository.LoginRepository;

import javax.inject.Inject;

/**
 * Created by 42524 on 2018/1/11.
 */

public class LoginActivityViewModel extends ViewModel {

    private LoginRepository loginRepository;

    private LoginAction loginAction;

    @Inject
    public LoginActivityViewModel(LoginRepository loginRepository) {
        this.loginRepository = loginRepository;
    }


    public LiveData<Resource<Login>> login(String phone, String pwd) {
        return loginRepository.login(phone, pwd);
    }


    public boolean isLoggingIn() {
        return loginAction != null && loginAction.isLoggingIn();
    }

    public synchronized void startLoginSafely(LoginParams loginParams) {
        if (isLoggingIn()) {
            return;
        }
        startLogin(loginParams);
    }

    public synchronized void startLogin(final LoginParams loginParams) {
        if (loginAction != null && loginAction.isLoggingIn()) {
            return;
        }
        loginAction = new LoginAction();
        ThreadUtil.async(() ->
                loginAction.login(loginParams)
        );
    }

    public synchronized void forceStopLogin() {
        if (loginAction != null) {
            loginAction.stopLogin();
        }
        loginAction = null;
    }

}
